import grok
from zope import interface, schema
from app import z3cwidget_test
import tempfile

# imports needed by some widgets from z3c.widget
from zope.app.file.interfaces import IImage
from z3c.widget.image.widget import ImageWidget
from z3c.widget.tiny.widget import TinyWidget
from z3c.widget.dropdowndatewidget.widget import DropDownDateWidget
from z3c.widget.country import Country
from z3c.widget.country.widget import CountryInputDropdown

class IEvent(interface.Interface):
    """ A simple class used to show how to use widgets from z3c.widget
    """
    title = schema.TextLine(title=u"Title")
    image = schema.Object(title=u"Image", schema=IImage)
    begin = schema.Date(title=u"Begin")
    end = schema.Date(title=u"End")
    contents = schema.Text(title=u"Contents")
    country = Country(title=u"Country")

class Event(grok.Model):
    interface.implements(IEvent)

    def __init__(self, title, image=None, begin=None, end=None, contents=None, country=None):
        super(Event, self).__init__()
        self.title = title
        self.image = image
        self.begin = begin
        self.end = end
        self.contents = contents
        self.country = country

def customize_event_form(form_fields):
    """ Replace the default widgets with widgets from z3c.widget
    """
    form_fields['image'].custom_widget = ImageWidget
    form_fields['contents'].custom_widget = TinyWidget
    for f in ('begin', 'end'):
        form_fields[f].custom_widget = DropDownDateWidget
    form_fields['country'].custom_widgets = CountryInputDropdown
    return form_fields

class AddEvent(grok.AddForm):
    grok.context(z3cwidget_test)
    form_fields = customize_event_form(grok.AutoFields(Event))

    @grok.action('Add event')
    def add(self, **data):
        obj = Event(**data)
        name = data['title'].lower().replace(' ', '_')
        self.context[name] = obj

class Edit(grok.EditForm):
    form_fields = customize_event_form(grok.AutoFields(Event))

class Index(grok.DisplayForm):
    pass

class ShowEventImage(grok.View):
    grok.name('image')

    def render(self):
        content_type = self.context.image.contentType
        self.response.setHeader('Content-Type', content_type)
        # the use of tempfile is for optimization purposes 
        # writing the image to a tempfile and returning the
        # filehandle leads to better memory comsumption
        # We could use this instead:
        # return str(self.context.image.data)
        tf = tempfile.TemporaryFile()
        tf.write(self.context.image.data)
        return tf
